package 设计模式.观察者模式;


import java.util.ArrayList;
import java.util.List;

/**
 * 观察者模式
 * Observer相当于监听器 当被监听对象执行某个可被监听的方法时，会遍历通知这些监听器，从而做出反应
 *
 * @author kkmystery
 * @version 1.0 2021/7/5
 * @since 1.0.0
 */
public class ObserverPattern {

    public static void main(String[] args) {
        ConcreteObserver1 observer1 = new ConcreteObserver1();
        ConcreteObserver2 observer2 = new ConcreteObserver2();
        ConcreteSubject subject = new ConcreteSubject();
        subject.add(observer1);
        subject.add(observer2);

        subject.action();
    }
}

// 主体
abstract class Subject {
    protected List<Observer> observers = new ArrayList<Observer>();

    // 增加观察者
    public void add(Observer observer) {
        observers.add(observer);
    }

    // 删除观察者
    public void remove(Observer observer) {
        observers.remove(observer);
    }

    // 通知观察者
    public abstract void notifyObserver(String msg);
}

class ConcreteSubject extends Subject {

    public void action() {
        System.out.println("ConcreteSubject做了某个动作");
        this.notifyObserver("action");
    }

    @Override
    public void notifyObserver(String msg) {
        System.out.println("具体目标发生改变，" + msg);
        System.out.println("--------------------");

        for (Object obs: observers) {
            ((Observer) obs).response();
        }
    }
}

interface Observer {
    // 反应
    void response();
}

class ConcreteObserver1 implements Observer {
    public void response() {
        System.out.println("具体观察者1 作出反应!");
    }
}

class ConcreteObserver2 implements Observer {
    public void response() {
        System.out.println("具体观察者2 作出反应!");
    }
}
